﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using Microsoft.SharePoint;

namespace SharePoint.DataMapper
{
	/// <summary>
	/// Вспомогательные методы
	/// </summary>
	public static class Helpers
	{
		#region Helpers for attributes

		/// <summary>
		/// Возвращает значение для поля Choice
		/// </summary>
		/// <param name="fieldInfo">The field info.</param>
		/// <returns></returns>
		public static string GetChoiceValue(FieldInfo fieldInfo)
		{
			Debug.Assert(fieldInfo != null);

			ChoiceAttribute attribute = AttributeService.GetAttribute<ChoiceAttribute>(fieldInfo);
			if (attribute == null)
			{
				return fieldInfo.Name;
			}
			return attribute.Choice;
		}

		private static readonly Dictionary<Type, Dictionary<string, string>> _enumValues = new Dictionary<Type, Dictionary<string, string>>();
		/// <summary>
		/// Возвращает список пар значений для перечисления заданного типа.
		/// </summary>
		/// <param name="enumType">Тип Enum</param>
		/// <returns></returns>
		public static Dictionary<string, string> GetEnumValues(Type enumType)
		{
			if (!_enumValues.ContainsKey(enumType))
			{
				Dictionary<string, string> values = new Dictionary<string, string>();
				foreach (string fieldName in Enum.GetNames(enumType))
				{
					FieldInfo fieldInfo = enumType.GetField(fieldName);
					values.Add(GetChoiceValue(fieldInfo), fieldName);
				}
				_enumValues.Add(enumType, values);
			}
			return _enumValues[enumType];
		}

		/// <summary>
		/// Get List Attribute foe SPList
		/// </summary>
		/// <param name="list">SPList</param>
		/// <returns>ListAttribute</returns>
		public static ListAttribute GetListAttribute(SPList list)
		{
			ListAttribute attribute = new ListAttribute(list.Title)
          	{
          		ListTemplateType = list.BaseTemplate,
          		Path = list.RootFolder.Url,
          		Description = list.Description
          	};
			return attribute;
		}

		public static ContentTypeAttribute GetContentTypeAttribute(SPContentType contentType)
		{
			ContentTypeAttribute attribute = new ContentTypeAttribute(contentType.Name, contentType.Id.ToString())
			{
                Description = contentType.Description,
				Group = contentType.Group,
				Hidden = contentType.Hidden,
                Sealed = contentType.Sealed
			};
			return attribute;
		}
		#endregion
	}
}